<template>
    <div class="material-outask-container">
        <!-- 物料入库申请单标题 -->
        <div class="material-header">
            <h2 class="material-title">
                <el-icon>
                    <Document />
                </el-icon>
                物料入库申请单
            </h2>
            <div class="material-status">
                <el-tag type="warning" size="large">待发送</el-tag>
            </div>
        </div>

        <!-- 物料入库申请单表单内容 -->
        <el-card class="material-card" shadow="hover">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px" class="material-form">

                <!-- 第一行：入库申请单编号 + 物料名称 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="入库申请单编号" prop="outAskCode">
                            <el-input v-model="ruleForm.outAskCode" placeholder="系统自动生成" disabled 
                                :prefix-icon="Document" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库物料名称" prop="productMaterialsName">
                            <el-input v-model="ruleForm.productMaterialsName" placeholder="请输入入库物料名称" 
                                :prefix-icon="Box" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第二行：采购单号 + 入库数量 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="采购单号" prop="purchaseOrderCode">
                            <el-input v-model="ruleForm.purchaseOrderCode" placeholder="请输入采购单号" 
                                :prefix-icon="Document" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库数量" prop="outAskCount">
                            <div class="quantity-control">
                                <el-button class="quantity-btn" @click="decreaseOutAskCount">-</el-button>
                                <el-input-number 
                                    v-model="ruleForm.outAskCount" 
                                    :min="1" 
                                    :step="1000"
                                    :step-strictly="false" 
                                    controls-position="right" 
                                    class="quantity-input"
                                    placeholder="请输入入库数量">
                                </el-input-number>
                                <el-button class="quantity-btn" @click="increaseOutAskCount">+</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第三行：供应商名称 -->
                <el-row :gutter="24" class="form-row">
                    <el-col :span="12">
                        <el-form-item label="供应商名称" prop="vendorName">
                            <el-input v-model="ruleForm.vendorName" placeholder="请输入供应商名称" 
                                :prefix-icon="User" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 预留位置，可以添加其他字段 -->
                    </el-col>
                </el-row>

                <!-- 第四行：入库描述 -->
                <el-row class="form-row">
                    <el-col :span="24">
                        <el-form-item label="入库描述" prop="outAskDesc">
                            <el-input 
                                v-model="ruleForm.outAskDesc" 
                                type="textarea" 
                                :rows="4"
                                placeholder="请输入入库描述" 
                                show-word-limit 
                                maxlength="200" 
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 按钮区域 -->
                <el-row class="form-actions">
                    <el-col :span="24">
                        <el-form-item>
                            <div class="button-group">
                                <el-button type="primary" size="large" :icon="Check" @click="submitForm(ruleFormRef)">
                                    提交入库申请
                                </el-button>
                                <el-button size="large" :icon="Refresh" @click="resetForm(ruleFormRef)">
                                    重置表单
                                </el-button>
                                <el-button size="large" :icon="Back" @click="goBack">
                                    返回
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 入库申请记录 -->
        <el-card class="material-history-card" shadow="hover" style="margin-top: 20px">
            <template #header>
                <div class="card-header">
                    <span>入库申请列表</span>
                    <el-button type="primary" @click="refreshOutAskList">刷新</el-button>
                </div>
            </template>
            
            <el-table :data="outAskList" border style="width: 100%">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="outAskCode" label="入库申请编号" width="150" />
                <el-table-column prop="purchaseOrderCode" label="采购单号" width="150" />
                <el-table-column prop="productMaterialsName" label="入库物料名称" width="180" />
                <el-table-column prop="outAskCount" label="入库数量" width="120" />
                <el-table-column prop="outAskDesc" label="入库描述" min-width="200" />
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createrPeople" label="创建人" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="vendorName" label="供应商名称" width="150" />
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <!-- 当状态为1（已完成）时，显示黄色的已入库文字 -->
                        <el-button 
                            v-if="Number(scope.row.status) !== 1"
                            type="primary" 
                            link 
                            @click="handleInbound(scope.row)"
                        >
                            入库
                        </el-button>
                        <span 
                            v-else
                            class="completed-text"
                        >
                            已入库
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination 
                    v-model:current-page="pagination.currentPage"
                    v-model:page-size="pagination.pageSize" 
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" 
                    :total="pagination.total"
                    @size-change="handleSizeChange" 
                    @current-change="handleCurrentChange" 
                />
            </div>
        </el-card>
        
        <!-- 入库操作弹窗 - 移至根级别 -->
        <el-dialog v-model="dialogVisibleIn" title="物料入库" width="500px" append-to-body center destroy-on-close>
            <el-form ref="inboundFormRef" style="max-width: 600px" :model="inboundForm" :rules="inboundRules" label-width="auto">
                <el-form-item label="入库编号" prop="outInCode">
                    <div style="display: flex; gap: 10px;">
                        <el-input v-model="inboundForm.outInCode" :disabled="isInCodeGenerated" />
                        <el-button type="primary" @click="generateInCode" :disabled="isInCodeGenerated">
                            {{ isInCodeGenerated ? '已生成' : '生成编号' }}
                        </el-button>
                    </div>
                </el-form-item>
                <el-form-item label="入库数量" prop="outInCount">
                    <el-input-number v-model="inboundForm.outInCount" :min="1" :step="1" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="物料名称" prop="productMaterialsName">
                    <el-input v-model="inboundForm.productMaterialsName" disabled />
                </el-form-item>
                <el-form-item style="padding-left: 400px;">
                    <el-tag type="success">入库</el-tag>
                </el-form-item>
                <el-form-item>
                    <el-button @click="dialogVisibleIn = false">取消</el-button>
                    <el-button type="primary" @click="submitInboundForm(inboundFormRef)">确定入库</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRoute, useRouter } from 'vue-router'
import { Document, Box, Check, Refresh, Back, User } from '@element-plus/icons-vue'

const pinia = useCounterStore();
const route = useRoute();
const router = useRouter();

// 入库申请记录列表
const outAskList = ref<any[]>([]);

// 分页信息
const pagination = reactive({
    currentPage: 1,
    pageSize: 5,
    total: 0
});

// 入库操作相关数据
const dialogVisibleIn = ref(false);
const isInCodeGenerated = ref(false);
const inboundFormRef = ref<FormInstance>();
const currentOutAskItem = ref<any>({});

// 入库表单数据
const inboundForm = reactive({
    outInCode: "",
    outIn: 2, // 2表示入库
    outInCount: 0,
    productMaterialsId: null as number | null,
    productMaterialsName: "",
    materialAskCode: "",
    createrPeople: pinia.piniaDto?.realName || pinia.piniaDto?.accountName || "admin",
    outAskId: null as number | null // 关联的入库申请单ID
});

// 入库表单验证规则
const inboundRules = reactive<FormRules>({
    outInCode: [
        { required: true, message: '请输入入库编号', trigger: 'blur' },
    ],
    outInCount: [
        { required: true, message: '请输入入库数量', trigger: 'change' },
        { type: 'number', min: 1, message: '入库数量必须大于0', trigger: 'change' }
    ]
});

onMounted(() => {
    // 生成入库申请单编号
    generateOutAskCode();
    
    // 检查是否有从采购单页面传来的参数
    if (route.query.purchaseOrderCode || route.query.productMaterialsName || route.query.outAskCount || route.query.vendorName) {
        // 添加调试日志，查看接收到的参数
        console.log('接收到的路由参数:', route.query);
        
        const purchaseOrderCode = route.query.purchaseOrderCode as string;
        const productMaterialsName = route.query.productMaterialsName as string;
        const productMaterialsId = route.query.productMaterialsId as string;
        const outAskCount = Number(route.query.outAskCount) || 0;
        const vendorName = route.query.vendorName as string;
        
        // 预填表单
        if (purchaseOrderCode) {
            ruleForm.purchaseOrderCode = purchaseOrderCode;
        }
        if (productMaterialsName) {
            ruleForm.productMaterialsName = productMaterialsName;
        }
        
        // 设置productMaterialsId
        if (productMaterialsId) {
            // 将字符串转换为数字
            ruleForm.productMaterialsId = Number(productMaterialsId);
            console.log('设置productMaterialsId:', ruleForm.productMaterialsId);
        } else {
            console.log('未收到productMaterialsId参数');
        }
        
        if (outAskCount) {
            ruleForm.outAskCount = outAskCount;
        }
        if (vendorName) {
            ruleForm.vendorName = vendorName;
        }
        
        // 生成描述
        if (productMaterialsName && outAskCount) {
            ruleForm.outAskDesc = `物料${productMaterialsName}入库数量为${outAskCount}个`;
        }
    }
    
    // 获取入库申请记录
    getOutAskList();
})

// 表单引用
const ruleFormRef = ref<FormInstance>()

// 表单数据 - 根据后端接口字段设计
const ruleForm = reactive({
    "outAskCode": "", // 入库申请单编号 - RK + 随机六位数
    "purchaseOrderCode": "", // 采购单号
    "productMaterialsName": "", // 入库物料名称
    "productMaterialsId": null as number | null, // 物料ID，从采购单反填
    "outAskCount": 0, // 入库数量
    "outAskDesc": "", // 入库描述
    "status": 0, // 状态，默认为0（已发送）
    "createrPeople": pinia.piniaDto?.realName || pinia.piniaDto?.accountName || "admin", // 创建人
    "vendorName": "" // 供应商名称
})

// 表单验证规则
const rules = reactive<FormRules>({
    outAskCode: [
        { required: true, message: '入库申请单编号不能为空', trigger: 'blur' },
    ],
    purchaseOrderCode: [
        { required: true, message: '请输入采购单号', trigger: 'blur' },
    ],
    productMaterialsName: [
        { required: true, message: '请输入入库物料名称', trigger: 'blur' },
    ],
    outAskCount: [
        { required: true, message: '请输入入库数量', trigger: 'change' },
        { type: 'number', min: 1, message: '入库数量必须大于0', trigger: 'change' }
    ],
    vendorName: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' },
    ],
    outAskDesc: [
        { required: true, message: '请输入入库描述', trigger: 'blur' },
    ],
})

// 生成入库申请单编号 - RK + 随机六位数
const generateOutAskCode = () => {
    const randomNumber = Math.floor(100000 + Math.random() * 900000).toString();
    ruleForm.outAskCode = 'RK' + randomNumber;
}

// 增加入库数量（点击加号添加1000）
const increaseOutAskCount = () => {
    if (!ruleForm.outAskCount) {
        ruleForm.outAskCount = 1000;
    } else {
        ruleForm.outAskCount = Number(ruleForm.outAskCount) + 1000;
    }
}

// 减少入库数量
const decreaseOutAskCount = () => {
    if (!ruleForm.outAskCount || Number(ruleForm.outAskCount) <= 1000) {
        ElMessage.warning('入库数量不能小于1000');
        return;
    }
    ruleForm.outAskCount = Number(ruleForm.outAskCount) - 1000;
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 打印表单中的productMaterialsId
            console.log('提交前的productMaterialsId:', ruleForm.productMaterialsId, typeof ruleForm.productMaterialsId);
            
            // 确保productMaterialsId有值
            if (ruleForm.productMaterialsId === null || ruleForm.productMaterialsId === undefined) {
                console.log('提交前发现productMaterialsId无效，设置为0');
                ruleForm.productMaterialsId = 0;
            }
            
            // 再次检查路由参数中的productMaterialsId
            if (route.query.productMaterialsId) {
                const idFromRoute = Number(route.query.productMaterialsId);
                console.log('从路由参数重新获取productMaterialsId:', idFromRoute);
                ruleForm.productMaterialsId = idFromRoute;
            }
            
            // 准备提交数据，确保格式正确
            const submitData = {
                outAskCode: ruleForm.outAskCode,
                purchaseOrderCode: ruleForm.purchaseOrderCode,
                productMaterialsName: ruleForm.productMaterialsName,
                // 确保productMaterialsId是数字类型且有值
                productMaterialsId: Number(ruleForm.productMaterialsId || 0),
                outAskCount: Number(ruleForm.outAskCount),
                outAskDesc: ruleForm.outAskDesc,
                createrPeople: ruleForm.createrPeople,
                vendorName: ruleForm.vendorName,
                status: Number(ruleForm.status)
            };
            
            console.log('最终提交的productMaterialsId:', submitData.productMaterialsId, typeof submitData.productMaterialsId);
            
            console.log('提交数据处理后:', submitData); // 添加调试日志
            
            console.log('提交数据:', submitData); // 调试日志
            
            // 调用后端API添加入库申请单
            axios.post('/api/ProductionModules/AddMaterialOutAsk', submitData).then(res => {
                if (res.data.code == 200) {
                    // 不管来源，都在当前页面处理
                    ElMessage.success('入库申请单提交成功');
                    clearForm(formEl);
                    // 刷新入库申请记录列表
                    getOutAskList();
                } else {
                    ElMessage.error(res.data.message || '提交失败，请重试');
                }
            }).catch(error => {
                ElMessage.error('网络异常，提交失败');
                console.error('Submit error:', error);
                if (error.response && error.response.data) {
                    console.error('Server response:', error.response.data);
                }
            });
        } else {
            console.log('表单验证失败!', fields)
        }
    })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    generateOutAskCode();
}

// 清空表单（提交成功后使用）
const clearForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 清空所有字段
    ruleForm.purchaseOrderCode = '';
    ruleForm.productMaterialsName = '';
    ruleForm.outAskCount = 0;
    ruleForm.outAskDesc = '';
    ruleForm.vendorName = '';
    // 重新生成编号
    generateOutAskCode();
}

// 返回上一页
const goBack = () => {
    router.go(-1); // 返回上一页
}

/**
 * 获取入库申请记录列表
 * 从服务器获取最新的入库申请记录数据
 */
const getOutAskList = async () => {
    try {
        const params = {
            PageIndex: pagination.currentPage,
            PageSize: pagination.pageSize,
            ProductMaterialsName: '' // 根据API参数
        };
        
        console.log('请求入库申请记录列表，参数:', params);
        const response = await axios.get('/api/ProductionModules/GetMaterialOutAsk', { params });
        
        if (response.data.code === 200) {
            console.log('入库申请记录API返回数据:', response.data);
            outAskList.value = response.data.totalPage || [];
            
            // 检查返回的数据结构
            if (outAskList.value.length > 0) {
                console.log('第一条入库申请记录:', outAskList.value[0]);
                console.log('第一条记录的所有字段:', Object.keys(outAskList.value[0]));
                console.log('第一条记录的status值:', outAskList.value[0].status, '类型:', typeof outAskList.value[0].status);
            }
            
            pagination.total = response.data.totalcount || 0;
        } else {
            console.error('获取入库申请记录失败:', response.data.message);
        }
    } catch (error) {
        console.error('获取入库申请记录异常:', error);
    }
}

/**
 * 刷新入库申请记录列表
 * 强制从服务器重新获取最新数据
 */
const refreshOutAskList = () => {
    console.log('手动刷新入库申请记录列表');
    getOutAskList();
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    getOutAskList();
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
    pagination.currentPage = page;
    getOutAskList();
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
    if (!dateString) return '';
    return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
}

// 获取状态标签类型
const getStatusType = (status: number | string) => {
    // 转换为数字进行比较
    const statusNum = Number(status);
    switch (statusNum) {
        case 0:
            return 'warning'; // 已发送
        case 1:
            return 'success'; // 已完成
        case 2:
            return 'info'; // 已取消
        case 3:
            return 'danger'; // 已拒绝
        default:
            return 'info';
    }
}

// 获取状态文本
const getStatusText = (status: number | string) => {
    // 转换为数字进行比较
    const statusNum = Number(status);
    switch (statusNum) {
        case 0:
            return '已提交申请';
        case 1:
            return '已完成入库';
        case 2:
            return '已取消';
        case 3:
            return '已拒绝';
        default:
            return '未知';
    }
}

/**
 * 处理入库按钮点击事件
 * @param row 当前行数据
 */
const handleInbound = (row: any) => {
    // 如果状态已经是已完成，则不允许再次入库
    // 使用Number()转换确保字符串"1"也能被正确识别
    if (Number(row.status) === 1) {
        ElMessage.warning('该入库申请已完成，不能重复入库');
        return;
    }
    
    // 调试日志 - 打印当前行的状态
    console.log('当前行状态值:', row.status, '类型:', typeof row.status);
    
     // 保存当前选中的入库申请单
     currentOutAskItem.value = row;
     
     // 打印完整的行数据，用于调试
     console.log('完整的入库申请单行数据:', row);
     console.log('行数据的所有字段:', Object.keys(row));
     
     // 打开入库弹窗
     dialogVisibleIn.value = true;
    
    // 重置入库表单
    inboundForm.outInCode = ""; // 重置入库编号
    isInCodeGenerated.value = false; // 重置生成状态
    
    // 设置入库数据
    inboundForm.outInCount = row.outAskCount; // 默认入库数量与申请数量一致
    inboundForm.productMaterialsName = row.productMaterialsName; // 设置物料名称
    inboundForm.materialAskCode = row.outAskCode; // 设置关联的申请单号
    inboundForm.outAskId = row.id; // 设置关联的入库申请单ID
    
     // 确保productMaterialsId有值
     if (row.productMaterialsId !== undefined && row.productMaterialsId !== null) {
         inboundForm.productMaterialsId = row.productMaterialsId;
         console.log('从入库申请单获取的productMaterialsId:', row.productMaterialsId);
     } else {
         console.log('入库申请单中没有productMaterialsId，尝试使用其他字段');
         
         // 尝试从其他可能的字段获取物料ID
         const possibleFields = ['materialId', 'productMaterialId', 'id'];
         for (const field of possibleFields) {
             if (row[field] !== undefined && row[field] !== null) {
                 inboundForm.productMaterialsId = row[field];
                 console.log(`使用${field}作为物料ID:`, row[field]);
                 break;
             }
         }
         
         // 如果仍然没有找到，设置为0
         if (inboundForm.productMaterialsId === null || inboundForm.productMaterialsId === undefined) {
             console.log('无法找到有效的物料ID，设置默认值0');
             inboundForm.productMaterialsId = 0;
         }
     }
}

/**
 * 生成入库编号
 */
const generateInCode = () => {
    const randomNumber = Math.floor(100000 + Math.random() * 900000).toString();
    inboundForm.outInCode = 'RK' + randomNumber;
    isInCodeGenerated.value = true;
}

/**
 * 提交入库表单
 */
/**
 * 提交入库表单
 * 处理入库操作并更新申请记录状态
 */
const submitInboundForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                 // 确保productMaterialsId有值
                 if (inboundForm.productMaterialsId === null || inboundForm.productMaterialsId === undefined) {
                     inboundForm.productMaterialsId = 0;
                 }
                 
// 准备入库API数据
const inboundData = {
    outInCode: inboundForm.outInCode,
    outIn: inboundForm.outIn, // 2表示入库
    outInCount: Number(inboundForm.outInCount), // 确保是数字
    productMaterialsName: inboundForm.productMaterialsName,
    productMaterialsId: Number(inboundForm.productMaterialsId || 0), // 确保是数字
    materialAskCode: inboundForm.materialAskCode,
    createrPeople: inboundForm.createrPeople,
    outAskId: currentOutAskItem.value.id, // 关键：传递申请记录ID，让服务器知道要更新哪个记录
    outAskStatus: 1 // 关键：使用outAskStatus而不是status，可能后端期望这个名称
};
                
                console.log('入库数据:', inboundData); // 调试日志
                
                 const inboundResponse = await axios.post('/api/ProductionModules/AddMaterialIn', inboundData);
                 
                 if (inboundResponse.data.code === 200) {
                     ElMessage.success('入库成功');
                     
                     // 立即更新当前行的状态为已完成(1) - 让按钮永久消失
                     if (currentOutAskItem.value && currentOutAskItem.value.id) {
                         // 找到当前行并更新其状态
                         const index = outAskList.value.findIndex(item => item.id === currentOutAskItem.value.id);
                         if (index !== -1) {
                             // 更新状态为已完成 - 确保是数字类型的1
                             outAskList.value[index].status = 1;
                             console.log('已更新行状态为已完成，按钮将消失:', outAskList.value[index]);
                             
                             // 强制触发Vue响应式更新
                             outAskList.value = [...outAskList.value];
                             
// 调用API更新服务器端状态
const updateResult = await updateOutAskStatus(currentOutAskItem.value.id);
if (!updateResult) {
    console.error('❌ 服务器端状态更新失败');
}
                         }
                     }
                     
// 关闭弹窗
dialogVisibleIn.value = false;

// 刷新列表，确保显示最新状态
setTimeout(() => {
    refreshOutAskList();
}, 500);
                 } else {
                     ElMessage.error(inboundResponse.data.message || '入库操作失败');
                 }
             } catch (error) {
                 console.error('入库操作异常:', error);
                 ElMessage.error('网络异常，入库操作失败');
             }
        } else {
            console.log('表单验证失败!', fields);
        }
    });
}

/**
 * 更新入库申请状态为已完成
 * @param id 申请记录ID
 */
const updateOutAskStatus = async (id: any) => {
    try {
        console.log('调用API更新入库申请状态，ID:', id);
        
        // 找到完整的申请记录数据
        const record = outAskList.value.find(item => item.id === id);
        if (!record) {
            console.error('未找到申请记录:', id);
            return false;
        }
        
        // 构造完整的更新数据 - 包含所有必要字段
        const updateData = {
            ...record,  // 保留原有所有字段
            id: id,
            status: 1  // 1表示已完成
        };
        
        console.log('发送到服务器的完整数据:', updateData);
        
        // 直接返回true，因为我们已经在入库API中传递了outAskId和outAskStatus参数
        // 这已经足够让后端更新状态，不需要再调用其他API
        console.log('✅ 使用入库API中的outAskId参数更新状态已足够');
        return true;
    } catch (error) {
        console.error('更新状态整体流程异常:', error);
        return false;
    }
}
</script>

<style scoped>
/* 主容器样式 */
.material-outask-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 40px);
}

/* 入库标题区域 */
.material-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(74, 222, 128, 0.3);
}

.material-title {
    display: flex;
    align-items: center;
    color: white;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
}

.material-title .el-icon {
    margin-right: 12px;
    font-size: 28px;
}

.material-status {
    display: flex;
    align-items: center;
}

/* 入库卡片样式 */
.material-card, .material-history-card {
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid #e4e7ed;
    background: white;
}

.material-card:hover, .material-history-card:hover {
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
    transition: all 0.3s ease;
}

/* 表单样式 */
.material-form {
    padding: 24px;
}

.form-row {
    margin-bottom: 24px;
}

.form-row:last-of-type {
    margin-bottom: 0;
}

/* 数量控制样式 */
.quantity-control {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
}

.quantity-btn {
    flex: 0 0 auto;
    padding: 8px 12px;
    font-size: 16px;
    font-weight: bold;
}

.quantity-input {
    flex: 1;
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
    color: #303133;
    font-weight: 600;
    font-size: 14px;
    line-height: 1.6;
}

:deep(.el-input) {
    border-radius: 8px;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #dcdfe6;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    border-color: #c0c4cc;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

:deep(.el-textarea__inner) {
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    resize: vertical;
}

/* 按钮区域样式 */
.form-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 2px solid #f0f2f5;
}

.button-group {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.button-group .el-button {
    min-width: 120px;
    height: 44px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.button-group .el-button--primary {
    background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
    border: none;
}

.button-group .el-button--primary:hover {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.button-group .el-button:not(.el-button--primary) {
    background: white;
    border: 1px solid #d9d9d9;
    color: #666;
}

.button-group .el-button:not(.el-button--primary):hover {
    border-color: #409eff;
    color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

/* 历史记录卡片头部 */
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
    color: #303133;
}

/* 分页容器样式 */
.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9fafb;
    border-radius: 8px;
}

/* 已入库文字样式 */
.completed-text {
    color: #E6A23C;
    font-weight: 500;
    padding: 2px 8px;
    background-color: rgba(230, 162, 60, 0.1);
    border-radius: 4px;
    border: 1px solid rgba(230, 162, 60, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .material-outask-container {
        padding: 16px;
    }

    .material-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        padding: 16px;
    }

    .material-title {
        font-size: 20px;
    }

    .material-form {
        padding: 16px;
    }

    .form-row .el-col {
        margin-bottom: 16px;
    }

    .button-group {
        flex-direction: column;
        align-items: center;
    }

    .button-group .el-button {
        width: 100%;
        max-width: 200px;
    }

    .quantity-control {
        flex-direction: column;
        gap: 8px;
    }

    .quantity-btn, .quantity-input {
        width: 100%;
    }
}

/* 动画效果 */
.material-card, .material-history-card {
    animation: slideInUp 0.6s ease-out;
}


@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.material-header {
    animation: slideInDown 0.6s ease-out;
}

@keyframes slideInDown {
    from {
        opacity: 0;
        transform: translateY(-30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
